package com.chis.netty.mqtt.server;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;

import com.chis.netty.utils.ConfigProperVal;
import com.chis.netty.utils.ServerSslContextFactory;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleStateHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

/**
 * 
 * @author 
 * @date 2015-5-11
 * @AppServerInitializer.java
 */
public class MqttServerInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		try {
			//ssl
			SSLEngine sslEngine = ServerSslContextFactory.getServerContext().createSSLEngine();
			sslEngine.setUseClientMode(false);
			ch.pipeline().addLast(new SslHandler(sslEngine));
			//mqtt协议
			ChannelPipeline p = ch.pipeline();
			p.addLast("decoder", new MqttDecoder());
			p.addLast("encoder", MqttEncoder.INSTANCE);
			p.addLast("mqttHander", new MqttServerHandler());
			//IdleStateHandler实现心跳检测，采用单向心跳，避免大量连接造成资源消耗,客户端5秒没有读写，触发超时
	        p.addLast(new IdleStateHandler(5,5, 5, TimeUnit.SECONDS));
		} catch (Exception e) {
			System.out.println("error:"+e.getMessage());
			e.printStackTrace();
		}
	}
}
